package com.wisenet.wx.util;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.apache.log4j.Logger;

import com.alibaba.fastjson.JSONObject;
import com.wisenet.common.WxConst;
import com.wisenet.entity.LeaveWord;
import com.wisenet.entity.SportWearOrder;
import com.wisenet.pojo.Template;
import com.wisenet.util.VeDate;

public class TemplateMessageManager {
	private static Logger logger = Logger.getLogger(TemplateMessageManager.class);
	
	/**
	 * 订单发货详情、提问回答详情
	 * @param leaveWord
	 * @return
	 */
	public static Map<String, Object> getKeywordInfo(LeaveWord leaveWord) {
		Map<String, Object> keywordData = null;
		if (!"".equals(leaveWord.getAnswer())) {
			keywordData = setKeywords(new Object[] {
			   leaveWord.getContent(),
			   VeDate.DateToString(leaveWord.getCreateDate()),
			   leaveWord.getAnswer()
			});
		} else {
			keywordData = setKeywords(new Object[] {
			   leaveWord.getMoney() + "元",
			   "充值成功",
			   leaveWord.getCount() + "次图文识别",
			   VeDate.DateToString(new Date()),
			   Math.abs(leaveWord.getFormid().hashCode())
			});
		}
		return keywordData;
	}
	
	/**
	 * 订单发货消息、提问回答消息
	 * @param leaveWord
	 * @param token
	 * @param templateId
	 * @return
	 */
	public static boolean sendOrderMessage(LeaveWord leaveWord, String token, String templateId) {
		Template template = new Template();
		template.setPage("pages/index/index");
		template.setTemplate_id(templateId);
		template.setTouser(leaveWord.getUid());
		template.setForm_id(leaveWord.getFormid());
		template.setData(getKeywordInfo(leaveWord));
		
		JSONObject message = (JSONObject) JSONObject.toJSON(template);
		logger.info("templateMsg: " + message);
		
		JSONObject json = WeixinUtil.httpRequest(WxConst.TEMPLATE_URL + token, "POST", message);
		logger.info("send mesaage: " + json);
		
		return json.getIntValue("errcode") == 0 ? true : false;
	}
	
	/**
	 * 运动服支付成功消息
	 * @param order
	 * @param token
	 * @return
	 */
	public static boolean sendPaySuccessMessage(SportWearOrder order, String token) {
		// 商品详情、商品数量、付款金额、付款时间、订单编号
		Object keywordData = setKeywords(new Object[] {
			order.getTitle() + " 颜色：" + order.getColor() + " 尺码：" + order.getSize(),
			order.getCount(),
			order.getTotalPrice() + "元",
			VeDate.DateToString(order.getCreateTime()),
			order.getOutTradeNo()
		});
		Template template = new Template();
		template.setPage("pages/index/index");
		template.setData(keywordData);
		template.setTouser(order.getUid());
		template.setForm_id(order.getFormId());
//		template.setTemplate_id(WxConst.SportShopConst.ORDER_FORM_ID);
		
		try {
			JSONObject message = (JSONObject) JSONObject.toJSON(template);
			logger.info("templateMsg: " + message);
			JSONObject json = WeixinUtil.httpRequest(WxConst.TEMPLATE_URL + token, "POST", message);
			logger.info("send mesaage: " + json);
			return json.getIntValue("errcode") == 0 ? true : false;
		} catch (Exception ex) {
			logger.info("JSON error: " + ex.getMessage());
			return false;
		}
	}
	
	/**
	 * 运动服发货通知消息
	 * @param order
	 * @param token
	 * @return
	 */
	public static boolean sendExpressMessage(SportWearOrder order, String token) {
		// 快递状态、商品名称、快递单号、发货时间
		Object keywordData = setKeywords(new Object[] {
			"正在派送中",
			order.getTitle() + " 颜色：" + order.getColor() + " 尺码：" + order.getSize(),
			VeDate.DateToString(order.getCreateTime()),
			order.getPostId()
		});
		Template template = new Template();
		template.setData(keywordData);
		template.setTouser(order.getUid());
		template.setForm_id(order.getPrepayId());// prepayId可用3次
		template.setEmphasis_keyword("keyword1.DATA");
//		template.setTemplate_id(WxConst.SportShopConst.POST_FORM_ID);
		template.setPage(String.format("pages/express/express?postid=%s&type=%s", order.getPostId(), order.getPostType()));
		
		try {
			JSONObject message = (JSONObject) JSONObject.toJSON(template);
			logger.info("templateMsg: " + message);
			JSONObject json = WeixinUtil.httpRequest(WxConst.TEMPLATE_URL + token, "POST", message);
			logger.info("send mesaage: " + json);
			return json.getIntValue("errcode") == 0 ? true : false;
		} catch (Exception ex) {
			logger.info("JSON error: " + ex.getMessage());
			return false;
		}
	}
	
	/**
	 * 设置模板消息参数
	 * @param args
	 * @return
	 */
	public static Map<String, Object> setKeywords(Object... args) {
		Map<String, Object> keywords = new HashMap<>();
		for (int i = 0; i < args.length; i ++) {
			keywords.put("keyword" + (i+1), setKeyword(args[i]));
		}
		return keywords;
	}
	
	/**
	 * keyword赋值
	 * @param value
	 * @return
	 */
	public static Object setKeyword(Object value) {
		String valueJson = "{\"value\":\"%s\",\"color\":\"%s\"}";
		return JSONObject.parse(String.format(valueJson, value, "#173177"));
	}
	
	public static Object setValue(Object value) {
		String valueJson = "{\"value\":\"%s\"}";
		return JSONObject.parse(String.format(valueJson, value));
	}
	
}
